package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mmall.common.ServerResponse;
import com.mmall.dao.ArticleMapper;
import com.mmall.pojo.Article;
import com.mmall.service.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @CLASS ArticleServiceimpl
 * @DESCRIPTION TODO
 * @AUTHor tang
 * @Date 2019-08-23 14:04
 * @VERSION 1.0
 **/
@Service("iArticleService")
public class ArticleServiceimpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    public ServerResponse<PageInfo> list(Integer userId, int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Article> articleList = articleMapper.selectArticleUserId(userId);
        PageInfo pageInfo = new PageInfo(articleList);
        pageInfo.setList(articleList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    public ServerResponse<String> updateSave(Integer userId,String userName, Article article){
        article.setUserId(userId);
        // 修改
        if (article.getId()!=null){
            int count = articleMapper.updateByUserKeySelective(article);
            if (count>0){
                return ServerResponse.createBySuccessMessage("修改文章成功");
            }
            // 新增
        }else {
            article.setUserName(userName);
            int count = articleMapper.insert(article);
            if (count>0){
                return ServerResponse.createBySuccessMessage("新增文章成功");
            }
        }
        return ServerResponse.createByErrorMessage("新增修改文章失败");
    }

    public ServerResponse<String> delete(Integer userId, Integer articleId){
        if (articleId==null){
            ServerResponse.createByErrorMessage("文章id不能为空");
        }
        int count = articleMapper.deleteArticleUserId(userId,articleId);
        if (count>0) return ServerResponse.createBySuccessMessage("删除文章成功");
        return ServerResponse.createByErrorMessage("删除文章失败");
    }

    public ServerResponse<Article> detail(Integer userId, Integer articleId){
        if (articleId==null){
            ServerResponse.createByErrorMessage("文章id不能为空");
        }
        Article article = articleMapper.selectByPrimaryKey(articleId);
        return ServerResponse.createBySuccess(article);
    }

}
